$(function(){ 
    var loading = $('#loading');
    window.cityList = cityList5;
    window.cityListapply = cityList5;
    var toggleLoading = function (isShow) {
        if (isShow) {
            loading.removeClass('hidden');
        } else {
            loading.addClass('hidden');
        }
    };
    $('#accounts-table tbody').on('click','.first-tr',function(){
        var secondTr = $(this).next('.second-tr');
        if (secondTr.is(":hidden")) {
            secondTr.show().css('border-top','none');
            secondTr.siblings('.second-tr').hide();
            $(this).siblings('.first-tr').css('border-bottom','1px solid #eee')
            $(this).css('border-bottom','none');
        } else {
            secondTr.hide().css('border-top','1px solid #eee');
            $(this).css('border-bottom','1px solid #eee');
        }
    });
    $('.close-tr').on('click',function(){
        $(this).closest('.second-tr').hide();
        $('.first-tr').css('border-top','1px solid #eee');
    });
    var status = $('#accounts-table .first-tr');
    $('.switch-btn').on('click',function(e){
        e.stopPropagation();
        var $this = $(this);
        var $firstTr = $this.closest('.first-tr');
        var $nextTr = $firstTr.next('.second-tr');
        var newValue = $this.children().attr('status');
        var hotel = $(this).attr('data-value');
        $me = $(this);
        ajaxRequest('/Home/DealerManage/setActive', {
            "hotel": hotel,
            "status": newValue,           
        }, 'post', function (data) {
            if(newValue==1){
                $this.html('<span status="0" style="color:red;">'+lang('dealer.block')+'</span>');
                $firstTr.removeClass('status-gray');
                $firstTr.children('.enddate').text(data.data);
                $nextTr.find('.enddate').text(data.data);
                $nextTr.removeClass('status-gray');  
                $nextTr.find('.changeYearsModal').show();
            }else{
                $this.html('<span status="1">'+lang('dealer.start')+'</span>');
                $firstTr.addClass('status-gray');
                $firstTr.children('.enddate').text(data.data);
                $nextTr.find('.enddate').text(data.data);
                $nextTr.addClass('status-gray');
                $nextTr.find('.changeYearsModal').hide();
            }
        }, null, $me);        
    })
    $('#againModal').inputValidate({
        submit: {
            query: '#submitAgain'
        },
        inputs: [{
            query: '#again-hotelName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('dealer.nameNull')
        },{
            query: '#again-address',
            regexp: /^.{1,50}$/,
            message: lang('dealer.address'),
            emptyMessage: lang('dealer.addressNull')
        },{
            query: '#again-contact-person',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.linkman'),
            emptyMessage: lang('dealer.linkmanNull')
        },{
            query: '#again-contact-num',
            regexp: window.commonRegexp.nameLength15,
            message: lang('dealer.mobile15'),
            emptyMessage: lang('dealer.mobileNull')
        }]
    });
    $('.again-btn').on('click',function(e){
        e.stopPropagation();
        $('#againModal').modal('show');
        var params = $(this).attr('data-json');
        params = JSON.parse(params); 
        var hotelname = params.hotelname;
        var cityname = params.cityname;
        var username = params.username;
        var mobile = params.mobile;
        var applyId = params.id;
        $('#again-hotelName').val(hotelname);
        $('#again-address').val(cityname);
        $('#again-contact-person').val(username);
        $('#again-contact-num').val(mobile);
            $('#submitAgain').on('click',function(){
                param = {
                    hotelname: $('#again-hotelName').val(),
                    address: $('#again-address').val(),
                    username: $('#again-contact-person').val(),
                    mobile: $('#again-contact-num').val(),
                    applyId:applyId,
                }
                $me = $(this);
                formInlineRight($me);
                ajaxRequest('/Home/DealerManage/saveHotel', param, 'post', null, null, $me);        
            })
    });

    $("#datePickerInput").datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        autoclose: true, 
        startDate : '2015-12-12',
        endDate : $("#datePickerInput").attr('enddate')
    });

    
    $('#addModal').inputValidate({
        submit: {
            query: '#submitAdd'
        },
        inputs: [{
            query: '#hotelName',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('dealer.nameNull')
        },{
            query: '#address',
            regexp: /^.{1,50}$/,
            message: lang('dealer.address'),
            emptyMessage: lang('dealer.addressNull')
        },{
            query: '#contact-person',
            regexp: window.commonRegexp.nameLength20,
            message: lang('book.linkman'),
            emptyMessage: lang('dealer.linkmanNull')
        },{
            query: '#contact-num',
            regexp: window.commonRegexp.mobile,
            message: lang('dealer.mobile'),
            emptyMessage: lang('dealer.mobileNull')
        }]
    });

    // 添加客栈
    $('#submitAdd').on('successSubmit.amos.inputValidate', function(e) {
        var param = {
                hotelname: $('#hotelName').val(),
                address: $('#address').val(),
                username: $('#contact-person').val(),
                mobile: $('#contact-num').val(),
                city: $('#cityContainerApply').find('.tag-selected-container .tag:last-child').data('value'),
                district: $('#districtContainerApply').find('.tag-selected-container .tag:first-child').data('value'),
                universalTime: $('#addRequestUniversalTime').val(),
                countryId : $('#addRequestUniversalTime option:selected').data('countryid'),
                areaCode: $('#accountAdd-container .areaCodeValue').text().trim(),
                currencyId: $('#addRequestMultiCurrency').val()
            },
        $me = $(this);
        if (!param.city || !param.district) {
            formInlineTip($me, lang('dealer.checkAddress'));
            return false;
        }
        formInlineRight($me);
        ajaxRequest('/Home/DealerManage/addHotel', param, 'post', null, null, $me);
    });
    //添加客栈类型
    $('.addHotel').on('click',function(){
        window.addStyles = true;
        $('#addHotelModal .tipsmall').removeClass('hidden');
    });
    $('.addCharity').on('click',function(){
        window.addStyles = false;
        $('#addHotelModal .tipsmall').addClass('hidden');
    });
    //添加客栈自动校验
    $('#addHotelModal').inputValidate({
        submit: {
            query: '#submitAddHotel'
        },
        inputs: [{
            query: '#user-mobile',
            regexp: window.commonRegexp.mobile,
            message: lang('dealer.mobile'),
            emptyMessage: lang('dealer.mobileNull')
        },{
            query: '#user-hotel',
            regexp: window.commonRegexp.nameLength20,
            message: lang('dealer.name'),
            emptyMessage: lang('dealer.nameNull')
        }]
    });
    // 添加客栈
    $('#submitAddHotel').on('successSubmit.amos.inputValidate', function(e) {
        var param = {
                hotel: $('#user-hotel').val().trim(),
                city: $('#cityContainer').find('.tag-selected-container .tag:last-child').data('value'),
                district: $('#districtContainer').find('.tag-selected-container .tag:first-child').data('value'),
                mobile: $('#user-mobile').val().trim(),
                enddate :$('#hotel-enddate').val().trim(),
                universalTime: $('#addHotelRequestUniversalTime').val(),
                areaCode: $('#addHotelModal .areaCodeValue').text().trim(),
                currencyId: $('#addHotelRequestMultiCurrency').val()
            },
            $me = $(this);
        if (!param.city || !param.district) {
            formInlineTip($me, lang('dealer.checkAddress'));
            return false;
        }
        formInlineRight($me);
        if(window.addStyles){
            ajaxRequest('/Home/DealerManage/addUserHotel', param, 'post', null, null, $me);
        }else{
            ajaxRequest('/Home/DealerManage/addUserCharityHotel', param, 'post', null, null, $me);
        }
    });
    //添加客栈自动校验
//  $('#addHotelModal .modal-content').inputValidate({
//      submit: {
//          query: '#submitAddCharity'
//      },
//      inputs: [{
//          query: '#user-mobile',
//          regexp: window.commonRegexp.mobile,
//          message: lang('dealer.mobile'),
//          emptyMessage: lang('dealer.mobileNull')
//      },{
//          query: '#user-hotel',
//          regexp: window.commonRegexp.nameLength20,
//          message: lang('dealer.name'),
//          emptyMessage: lang('dealer.nameNull')
//      }]
//  });
    // 添加客栈
//  $('#submitAddCharity').on('successSubmit.amos.inputValidate', function(e) {
//      var param = {
//              hotel: $('#user-hotel').val().trim(),
//              city: $('#cityContainer').find('.tag-selected-container .tag:last-child').data('value'),
//              district: $('#districtContainer').find('.tag-selected-container .tag:first-child').data('value'),
//              mobile: $('#user-mobile').val().trim(),
//              enddate :$('#hotel-enddate').val().trim(),
//              universalTime: $('#addHotelRequestUniversalTime').val(),
//              areaCode: $('#addHotelModal .areaCodeValue').text().trim(),
//          },
//          $me = $(this);
//      if (!param.city || !param.district) {
//          formInlineTip($me, lang('dealer.checkAddress'));
//          return false;
//      }
//      formInlineRight($me);
//      ajaxRequest('/Home/DealerManage/addUserCharityHotel', param, 'post', null, null, $me);
//  });    

    $("#hotel-enddate").datepicker({
        format: 'yyyy-mm-dd',
        language: "zh-CN",
        autoclose: true, 
        startDate :  new Date(),
        endDate : $("#datePickerInput").attr('enddate')
    });
    //城市初始化
    var getCitys = function(){
        var cityContainer = $('#cityContainer');
        var data = cityContainer.data('amos.tag');
        if (!data) {
            cityContainer.tag({
                removeAtSelected: true,
                selectedTagClickable: false,
                avaliable: window.cityList
            });
            cityContainer.on('selectedClick.amos.tag', selectedClickCity);
            cityContainer.on('beforeSelected.amos.tag', beforeSelectedCity);
        } else {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        }
        var districtContainer = $('#districtContainer');
        data = districtContainer.data('amos.tag');
        if (!data) {
            districtContainer.tag({
                removeAtSelected: false,
                selectedTagClickable: false
            });
            districtContainer.on('selectedClick.amos.tag', selectedClickDistrict);
            districtContainer.on('beforeSelected.amos.tag', beforeSelectedDistrict);
            districtContainer.tag('resetAvaliable');
        } else {
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
        }
    }
    $('#addHotelModal').on('show.bs.modal', function(e) {
        var cityId =parseInt($('#addHotelRequestUniversalTime option:selected').attr('value'))-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityList = citylistArr[i]; 
            }
        }
        getCitys();
        getCitys();
    });
    $("#addHotelRequestUniversalTime").change(function(){
        var cityId =parseInt($(this).val())-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityList = citylistArr[i]; 
            }
        }
        getCitys();
    });    
    
    
    var selectedClickCity = function(e, selectedIndex) {
        var cityContainer = $(this);
        var selectedTag = $(e.relatedTarget);
        // 0表示选择省份，1表示选择城市
        if (selectedIndex === 0) {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityList);
        } else {
            selectedTag.remove();
            cityContainer.tag('resetAvaliable');
            var value = cityContainer.find('.tag-selected-container .tag').data('value');
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        }
        var districtContainer = cityContainer.parents('form').find('.districtContainer');
        districtContainer.tag('resetSelected');
        districtContainer.tag('resetAvaliable');
    };
    var beforeSelectedCity = function(e, value) {
        var cityContainer = $(this);
        var selectedSize = cityContainer.find('.tag-selected-container .tag').size();
        // 0表示选择省份，1表示选择城市
        cityContainer.tag('resetAvaliable');
        if (selectedSize === 0) {
            var selectedProvinceCityList = getProvinceCities(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        } else {
            getCityDistricts(value, cityContainer);
        }
    };
    var selectedClickDistrict = function(e, selectedIndex) {
        var districtContainer = $(this);
        districtContainer.tag('resetSelected');
        districtContainer.find('.tag-avaliable-container').removeClass('hidden');
    };
    var beforeSelectedDistrict = function(e, value) {
        var districtContainer = $(this);
        districtContainer.find('.tag-avaliable-container').addClass('hidden');
    };
    var getCityDistricts = function(value, cityContainer) {
        var params = {};
        params.city = value;
        ajaxRequest('/Home/Position/getDistrict', params, 'post', function(data, cityContainer) {
            var districtContainer = cityContainer.parents('form').find('.districtContainer');
            districtContainer.find('.tag-avaliable-container').removeClass('hidden');
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
            if (data !== undefined) {
                districtContainer.tag('addAvaliable', data.data);
            }
        }, null, cityContainer);
    };
    var getProvinceCities = function(value) {
        var selectedProvinceCityList = [];
        for (var i = 0; i < window.cityList.length; i++) {
            if (window.cityList[i].id === value) {
                selectedProvinceCityList = window.cityList[i].cities;
                break;
            }
        }
        return selectedProvinceCityList;
    };

    //城市初始化
    var getCitysApply = function(){
        var cityContainer = $('#cityContainerApply');
        var data = cityContainer.data('amos.tag');
        if (!data) {
            cityContainer.tag({
                removeAtSelected: true,
                selectedTagClickable: false,
                avaliable: window.cityListapply
            });
            cityContainer.on('selectedClick.amos.tag', selectedClickCityApply);
            cityContainer.on('beforeSelected.amos.tag', beforeSelectedCityApply);
        } else {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityListapply);
        }
        var districtContainer = $('#districtContainerApply');
        data = districtContainer.data('amos.tag');
        if (!data) {
            districtContainer.tag({
                removeAtSelected: false,
                selectedTagClickable: false
            });
            districtContainer.on('selectedClick.amos.tag', selectedClickDistrictApply);
            districtContainer.on('beforeSelected.amos.tag', beforeSelectedDistrictApply);
            districtContainer.tag('resetAvaliable');
        } else {
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
        }
    }
    $('#addModal').on('show.bs.modal', function(e) {
        var cityId =parseInt($('#addRequestUniversalTime option:selected').attr('value'))-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityListapply = citylistArr[i]; 
            }
        }
        getCitysApply();
        getCitysApply();
    });
    $("#addRequestUniversalTime").change(function(){
        var cityId =parseInt($(this).val())-1 ;
        for(var i = 0;i<citylistArr.length;i++){
            if(cityId == i){
               window.cityListapply = citylistArr[i]; 
            }
        }
        getCitysApply();
    });    
    
    
    var selectedClickCityApply = function(e, selectedIndex) {
        var cityContainer = $(this);
        var selectedTag = $(e.relatedTarget);
        // 0表示选择省份，1表示选择城市
        if (selectedIndex === 0) {
            cityContainer.tag('resetSelected');
            cityContainer.tag('resetAvaliable');
            cityContainer.tag('addAvaliable', window.cityListapply);
        } else {
            selectedTag.remove();
            cityContainer.tag('resetAvaliable');
            var value = cityContainer.find('.tag-selected-container .tag').data('value');
            var selectedProvinceCityList = getProvinceCitiesApply(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        }
        var districtContainer = cityContainer.parents('form').find('.districtContainer');
        districtContainer.tag('resetSelected');
        districtContainer.tag('resetAvaliable');
    };
    var beforeSelectedCityApply = function(e, value) {
        var cityContainer = $(this);
        var selectedSize = cityContainer.find('.tag-selected-container .tag').size();
        // 0表示选择省份，1表示选择城市
        cityContainer.tag('resetAvaliable');
        if (selectedSize === 0) {
            var selectedProvinceCityList = getProvinceCitiesApply(value);
            cityContainer.tag('addAvaliable', selectedProvinceCityList);
        } else {
            getCityDistrictsApply(value, cityContainer);
        }
    };
    var selectedClickDistrictApply = function(e, selectedIndex) {
        var districtContainer = $(this);
        districtContainer.tag('resetSelected');
        districtContainer.find('.tag-avaliable-container').removeClass('hidden');
    };
    var beforeSelectedDistrictApply = function(e, value) {
        var districtContainer = $(this);
        districtContainer.find('.tag-avaliable-container').addClass('hidden');
    };
    var getCityDistrictsApply = function(value, cityContainer) {
        var params = {};
        params.city = value;
        ajaxRequest('/Home/Position/getDistrict', params, 'post', function(data, cityContainer) {
            var districtContainer = cityContainer.parents('form').find('.districtContainer');
            districtContainer.find('.tag-avaliable-container').removeClass('hidden');
            districtContainer.tag('resetSelected');
            districtContainer.tag('resetAvaliable');
            if (data !== undefined) {
                districtContainer.tag('addAvaliable', data.data);
            }
        }, null, cityContainer);
    };
    
    var getProvinceCitiesApply = function(value) {
        var selectedProvinceCityList = [];
        for (var i = 0; i < window.cityListapply.length; i++) {
            if (window.cityListapply[i].id === value) {
                selectedProvinceCityList = window.cityListapply[i].cities;
                break;
            }
        }
        return selectedProvinceCityList;
    };    

    //客栈部分结束  
    $('.changeYearsModal').click(function(){
        $('#changeTime').data('value',$(this).attr('data-value'));
        $('#datePickerInput').val($(this).attr('data-end'));
        $('#datePickerInput-start').val($(this).attr('data-start'));
    })
    $('#changeTime').on('click',function(){
        var endTime = $('#datePickerInput').val();
        var hotel = $(this).data('value');
        $me = $(this);
        formInlineRight($me);
        ajaxRequest('/Home/DealerManage/setEndtime', {
            "hotel": hotel,
            "enddate": endTime,            
        }, 'post', null, null, $me);
    })
    
    //判断是否显示多元货币
    $('#user-mobile').blur(function(){
        var areaCode = $(this).closest('.form-group').find('.areaCodeValue').text().trim();
        var mobile = $(this).val();
        ajaxRequest('/Home/DealerManage/adminCheckDefaultCurrency', {
            "areaCode": areaCode,
            "mobile": mobile,            
        }, 'post', function(data){
            var info = data.data;
            if(info.length !=0){
                $('#addHotelRequestMultiCurrency').attr('disabled',true);
                $("#addHotelRequestMultiCurrency").find("option[value='"+info.id+"']").attr("selected",true);
            }else{
                $('#addHotelRequestMultiCurrency').removeAttr('disabled');
            }
        }, null, $(this));
    });
})
